package com.firewolf.shiro;

import org.apache.shiro.codec.Base64;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.junit.Assert;
import org.junit.Test;

/**
 * 编码与解码
 * 
 * @author lx
 *
 */
public class EncodeAndDecode {

	/**
	 * 使用Base64编码与解码
	 */
	@Test
	public void base64() {
		String str = "hello";
		String base64Encoded = Base64.encodeToString(str.getBytes());
		System.out.println(base64Encoded);
		String str2 = Base64.decodeToString(base64Encoded);
		Assert.assertEquals(str, str2);
	}

	/**
	 * 十六进制编码解码
	 */
	@Test
	public void hex() {
		String str = "hello";
		String base64Encoded = Hex.encodeToString(str.getBytes());
		System.out.println(base64Encoded);
		String str2 = new String(Hex.decode(base64Encoded.getBytes()));
		Assert.assertEquals(str, str2);
	}

	/**
	 * CodecSupport用来把字符串和byte数组之间转换
	 */
	@Test
	public void codecSupport() {
		String str = "hello";
		byte[] bytes = CodecSupport.toBytes(str, "utf-8");
		String str2 = CodecSupport.toString(bytes, "utf-8");
		Assert.assertEquals(str, str2);
	}

	/**
	 * 生成随机数
	 */
	@Test
	public void testRandom() {
		SecureRandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
		randomNumberGenerator.setSeed("123".getBytes());
		System.out.println(randomNumberGenerator.nextBytes().toHex());
	}
}
